package mydemo.springcloudalibaba.cousumer.order.controller;

import lombok.extern.slf4j.Slf4j;
import mydemo.springcloudalibaba.api.common.entity.CommonResult;
import mydemo.springcloudalibaba.api.common.entity.Payment;
import mydemo.springcloudalibaba.cousumer.order.myLoadBalanced.MyLb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order")
@Slf4j
public class PaymentController {
    @Autowired
    private RestTemplate restTemplate;

//    private String baseUrl = "http://localhost:8001/payment/";
    private String baseUrl = "http://CLOUD-PAYMENT-SERVICE/payment/";

    @RequestMapping("/create")
    public CommonResult create(Payment payment){
        return new CommonResult(200,"成功", restTemplate.postForObject(baseUrl + "create", payment, CommonResult.class));
    }
    @RequestMapping("/get")
    public CommonResult get(Payment payment){
        return new CommonResult(200,"成功", restTemplate.getForObject(baseUrl + "/get/" + payment.getId(), CommonResult.class));
    }
    @RequestMapping("/getEntity")
    public CommonResult getEntity(Payment payment){
        ResponseEntity<CommonResult> ret = restTemplate.getForEntity(baseUrl + "/get/" + payment.getId(), CommonResult.class);
        return new CommonResult(200,"成功", ret);
    }

    /**
     * 自制负载请求测试
     */
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private MyLb myLb;
    @RequestMapping("/lb")
    public CommonResult lb(){
        ServiceInstance serviceInstance = myLb.instance(discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE"));
        if (null == serviceInstance){
            return new CommonResult(444,"失败");
        }
        ResponseEntity<Integer> ret = restTemplate.getForEntity(serviceInstance.getUri() + "payment/payment/lb/", Integer.class);
        return new CommonResult(200,"成功", ret);
    }
}
